package com.tetraq.grader;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class Percentage extends ListActivity {
	
	private final String DATABASE_NAME = "percentDB";
	private final String TABLE_NAME = "tPercents";
	private String theGrade = "";
	private String theWeight = "";
	private String theName = "";
	private int gradeNumber = 0;
	private int weightNumber = 0;
	private int totalWeight = 0;
	private double finalGrade = 0;
	
	EditText txtGrade;
	EditText txtName;
	EditText txtWeight;
	TextView txtWeightLeft;
	Button btnOK;
	Button btnClear;
	
	ArrayList<String> results = new ArrayList<String>();
	SQLiteDatabase myDB = null;
	ArrayAdapter<String> gradeAdapter;
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.percentbased);
        
        txtGrade = (EditText) findViewById(R.id.txtGradeP);
        txtWeight = (EditText) findViewById(R.id.txtWeight);
        txtName = (EditText) findViewById(R.id.txtLabelP);
        txtWeightLeft = (TextView) findViewById(R.id.txtWeightLeft);
        btnOK = (Button) findViewById(R.id.btnOKP);
        btnClear = (Button) findViewById(R.id.btnClear);
        
	    //results.add("None Yet");    
        //final ArrayAdapter<String> gradeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results);
        gradeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results);
	    
	    
	    /* Create a Database. */
	    try {
	    	myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
	   
	    	/* Create a Table in the Database. */
	    	myDB.execSQL("CREATE TABLE IF NOT EXISTS "
	    			+ TABLE_NAME
	    			+ " (id INTEGER PRIMARY KEY, Grade INT(3), Weight INT(3), Name VARCHAR);");
	    
	   
	    	
	    	
	    	buildAdapter();
	    	
	    	gradeAdapter.notifyDataSetChanged();
	    	this.setListAdapter((gradeAdapter));
	    	addWeight();
	    	if (totalWeight != 0) {
	    		int weightToGo = 100 - totalWeight;
	    		txtWeightLeft.setText("" + weightToGo + "% to go.");
	    	}
	    	if (totalWeight == 100) {
	    		
	    		btnOK.setEnabled(false);
	    		calculateGrade();
	    	}
	    	//Toast.makeText(this, "" + count, Toast.LENGTH_LONG ).show();
	    	
	    	
	    } catch(Exception e) {
	    	Log.e("Error", "Error", e);
	    
	    } finally {
	    	if(myDB != null)
	    		myDB.close();
	    }
	    
	    btnOK.setOnClickListener(new OnClickListener() 
	    { public void onClick(View v) {
	    	if(legalWeight()) {
	    		updateList(); 
	    		gradeAdapter.notifyDataSetChanged();
	    		addWeight();
	    		clearBoxes();}
	    	if(totalWeight == 100) {
	    		calculateGrade();
	    		btnOK.setEnabled(false);
	    	}
	    	}} );
	    
	
	}
	protected void onListItemClick(ListView l, View v, final int position, long id) {
		AlertDialog.Builder ask_del = new AlertDialog.Builder(this);
		ask_del.setCancelable(false)
		.setTitle("Delete?")
		.setMessage("Do you want to delete this grade?")
	    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int id) {
	        deleteGrade(position);
	        
	    	
	        gradeAdapter.notifyDataSetChanged();
	    } })
		.setNegativeButton("No", new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int id) {
	        return;
	    } }); 
        AlertDialog alert = ask_del.create();
        alert.show();
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		
	}
	
	public boolean legalWeight() {
		if (!blanks()) {
			int weightCheck = Integer.parseInt(txtWeight.getText().toString());
			if ((weightCheck + totalWeight) > 100) {
				Toast.makeText(this, "You are over 100%", Toast.LENGTH_LONG).show();
				return false;
			}
			return true;
		}
		Toast.makeText(this, "Something is blank!", Toast.LENGTH_LONG).show();
		return false;
	}
	
	public boolean noName() {
		return txtName.getText().toString().equals("");
	}
	
	public boolean blanks() {
		if (txtGrade.getText().toString().equals("") || txtWeight.getText().toString().equals(""))
			return true;
		else
			return false;
	}
	
	public int updateList() {
		if(!blanks()) {
			if (!noName()) 
				theName = txtName.getText().toString();
			theGrade = txtGrade.getText().toString();
			theWeight = txtWeight.getText().toString();
			gradeNumber = Integer.parseInt(theGrade);
			weightNumber = Integer.parseInt(theWeight);
		}
		else {
			Toast.makeText(this, "Something is blank!", Toast.LENGTH_SHORT).show();
			return 1;
		}
		try {
			myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
			if(noName()) 
				myDB.execSQL("INSERT INTO "
						+ TABLE_NAME
						+ " (Grade, Weight)"
						+ " VALUES (" + gradeNumber + ", " + weightNumber + ");");
			else
				myDB.execSQL("INSERT INTO "
						+ TABLE_NAME
						+ " (Grade, Weight, Name)"
						+ " VALUES (" + gradeNumber + ", " + weightNumber + ", '" + theName + "');");
		
			buildAdapter();
			
			
		} catch(Exception e) {
	    	Log.e("Error", "Error", e);
	    
	    } finally {
	    	if(myDB != null)
	    		myDB.close();
	    }
	    return 0;
			
	}
	
	public void buildAdapter() {
		results.clear();
		Cursor c = myDB.rawQuery("SELECT * FROM " + TABLE_NAME + ";", null);
    	int gradeColumn = c.getColumnIndex("Grade");
    	int weightColumn = c.getColumnIndex("Weight");
    	int nameColumn = c.getColumnIndex("Name");
    	int count = 0;
    	c.moveToFirst();
    	if (c != null) {
    		if(!(c.getCount()==0)) {
    			int i = 0;
    			
    			do {
    				i++;
    				String name = c.getString(nameColumn);
    				int grade = c.getInt(gradeColumn);
    				int weight = c.getInt(weightColumn);
    				results.add("" + grade + "\t" + weight + "%\t" + name);
    				
    				count++;
    			} while(c.moveToNext());
    		}
    		else
    			results.add("None yet!");
    	}
    	
		
	}
	
	public void clearBoxes() {
		txtName.setText("");
		txtGrade.setText("");
		txtWeight.setText("");
	}
	
	public void addWeight() {
		int addingWeight = 0;
		
			try {
				myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null); 
				Cursor c = myDB.rawQuery("SELECT Weight FROM " + TABLE_NAME + ";", null);
				int weightColumn = c.getColumnIndex("Weight");
				c.moveToFirst();
				if (c != null) {
					if(!(c.getCount()==0)) {
						int i = 0;
						
						do {
								i++;
								addingWeight += c.getInt(weightColumn);
						} while(c.moveToNext());
					}
				}
				//Toast.makeText(this, "" + addingWeight, Toast.LENGTH_LONG).show();
				totalWeight = addingWeight;
				int weightToGo = 100 - totalWeight;
				txtWeightLeft.setText("" + weightToGo + "% left to go.");
			} catch(Exception e) {
				Log.e("Error", "Error", e);
	    
			} finally {
				if(myDB != null)
					myDB.close();
			}
			
	}
	
	public void calculateGrade() {
		finalGrade = 0;
		try {
			myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
			Cursor c = myDB.rawQuery("SELECT * FROM " + TABLE_NAME + ";", null);
			int gradeColumn = c.getColumnIndex("Grade");
			int weightColumn = c.getColumnIndex("Weight");
			c.moveToFirst();
			if (c != null) {
				if(!(c.getCount()==0)) {
					int i = 0;
    			
					do {
							i++;
    				
							int grade = c.getInt(gradeColumn);
							int weight = c.getInt(weightColumn);
							finalGrade += grade*((double)weight/100);
    				
					} while(c.moveToNext());
				}
			}
		
			txtWeightLeft.setText("Final grade is " + finalGrade + "%");
		} catch(Exception e) {
			Log.e("Error", "Error", e);
		    
		} finally {
			if(myDB != null)
				myDB.close();
		}
	}
	
	public void deleteGrade(int position) {
		position++;
		try {
			myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
			myDB.execSQL("DELETE FROM "
					+ TABLE_NAME
					+ " WHERE id = " + position + ";");
			//updateList(); 
    		
    		addWeight();
		} catch(Exception e) {
			Log.e("Error", "Error", e);
		} finally {
			if(myDB !=null)
				myDB.close();
		}
		
	}
	
	public void recount(int position, long id) {
		Toast.makeText(this, "" + position + " " + id, Toast.LENGTH_LONG).show();
		/*try {
			int i = 0;
			myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
			myDB.execSQL("UPDATE "
					+ TABLE_NAME
					+ " SET " + i + " id = " + position + ";");
		} catch(Exception e) {
				Log.e("Error", "Error", e);
			    
			} finally {
				if(myDB != null)
					myDB.close();
			}
			gradeAdapter.notifyDataSetChanged();*/
		}
}